package com.ll.menu.user.cart;

import android.os.Bundle;

import com.droid.library.app.mvp.recycler.BaseRecyclerPresenter;
import com.ll.menu.user.app.entity.Food;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 购物车
 *
 * @author wangheng
 */

public class CartPresenter extends BaseRecyclerPresenter<ICartUI> {

    @Override
    public void onUICreate(Bundle savedInstanceState) {
        super.onUICreate(savedInstanceState);
        EventBus.getDefault().register(CartPresenter.this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CartEvent event){
        if(isUIDestroyed()){
            return;
        }
        switch (event.getEventType()){
            case CartEvent.TYPE_ADD_FOOD:
                requestList();
                break;
            case CartEvent.TYPE_REMOVE_FOOD:
                requestList();
                break;
            case CartEvent.TYPE_CHANGE_FOOD_NUMBER:
                if(CartManager.getInstance().getFoodTotalCount() == 0){
                    requestList();
                }
                break;
            case CartEvent.TYPE_REPLACE_FOOD_LIST:
                requestList();
                break;
            case CartEvent.TYPE_APPEND_FOOD_LIST:
                requestList();
                break;
            case CartEvent.TYPE_CLEAR_FOOD_LIST:
                requestList();
                break;
                default:
                    break;
        }
        if(!isUIDestroyed()){
            getUI().setTotalPrice(CartManager.getInstance().getTotalPrice());
        }
    }

    @Override
    public void onUIDestroy() {
        EventBus.getDefault().unregister(CartPresenter.this);
        super.onUIDestroy();
    }

    @Override
    protected void requestList(int page, int pageSize) {
        if(isUIDestroyed()){
            return;
        }
        ArrayList<Food> food = CartManager.getInstance().getFoodList();
        if(getUI().getAdapter() != null){
            getUI().getAdapter().resetDataList(food);
            getUI().setTotalPrice(CartManager.getInstance().getTotalPrice());

            onRefreshCompleted(PAGE_FIRST,true,true);

        }
    }
}
